package com.amt.olcacon;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.amt.olcacon.bo.FileData;
import com.amt.olcacon.bo.GetProviderInfo;
import com.amt.olcacon.db.DerbyConfig;
import com.amt.olcacon.mapper.ProductProcessMapper;
import com.amt.olcacon.vo.request.ExchangeRequest;
import com.amt.olcacon.vo.request.FlowRequest;
import com.amt.olcacon.vo.request.ProcessRequest;
import io.micrometer.common.util.StringUtils;
import org.junit.jupiter.api.Test;
import org.openlca.core.DataDir;
import org.openlca.core.database.Derby;
import org.openlca.core.database.FlowPropertyDao;
import org.openlca.core.database.ProcessDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.meta.Exhaustive;
import java.io.IOException;
import java.util.*;

public class ImportAndCalcResults {


//    private final ProductProcessMapper productProcessMapper;
//
//    public ImportAndCalcResults(ProductProcessMapper productProcessMapper) {
//        this.productProcessMapper = productProcessMapper;
//    }

    @Test
    public void getProcessTree() throws IOException {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);

        FileData fileData = ExcelParserTwoTables.getFileData("");

        Map<String,String> processMap = fileData.getProduct();
        List<Map<String,String>> exchangeList =fileData.getExchange();

        // 首先获得 flow 的信息
        List<FlowRequest> flowRequestList = new ArrayList<>();

        exchangeList.forEach(flow -> {flow.put("id",String.valueOf(getSnowflakeId()));
            flow.put("refId",UUID.randomUUID().toString());
            FlowRequest flowRequest = new FlowRequest();
            flowRequest.setId(Long.valueOf(flow.get("id")));
            flowRequest.setRefId(flow.get("refId"));
            flowRequest.setName(flow.get("name"));
            var flowproperty = new FlowPropertyDao(db).getForName(flow.get("unit_group")).getFirst();
            flowRequest.setFlowPropertyId(flowproperty.id);
            Map<Long ,Double> propertyFators = new HashMap<>();
            propertyFators.put(flowproperty.id,1.0);
            flowRequest.setPropertyFators(propertyFators);
            flowRequestList.add(flowRequest);});


        // 获得process 的信息
        ProcessRequest processRequest = getProcessRequest(db, processMap, exchangeList);

        System.out.println("===========flow=========");
        System.out.println(JSONUtil.toJsonStr(flowRequestList));
        System.out.println("===========Process=========");
        System.out.println(JSONUtil.toJsonStr(processRequest));


    }



    public ProcessRequest getProcessRequest(Derby db, Map<String,String> processMap,List<Map<String,String>> exchangeList){

        ProcessRequest processRequestList = new ProcessRequest();
        processRequestList.setId(getSnowflakeId());
        processRequestList.setRefId(UUID.randomUUID().toString());
        processRequestList.setName(processMap.get("process_name"));

        Map<String,String> productMainFlow = exchangeList.stream().filter(exchange -> exchange.get("type").equals("主产品")).findFirst().orElse(null);
        processRequestList.setFlowId(Long.valueOf(productMainFlow.get("id")));
        processRequestList.setFlowRefId(productMainFlow.get("refId"));

        List<ExchangeRequest> inputIds = new ArrayList<>();
        List<ExchangeRequest> outputIds = new ArrayList<>();

        for (Map<String, String> exchange : exchangeList) {

            String ioType = exchange.get("io_type");
            ExchangeRequest exchangeRequest = new ExchangeRequest();
            Long id = Long.valueOf(exchange.get("id"));
            String refId = exchange.get("refId");
            Double amount = Double.valueOf(exchange.get("enter_value"));
            Long providerId = null;
//            String provicer = exchange.get("background_name");
//            String providerLocation = exchange.get("country_code");
//            if(StringUtils.isNotBlank(provicer)){
//                List<GetProviderInfo> providerInfo = productProcessMapper.getProviderInfo(provicer, providerLocation);
//                if(!providerInfo.isEmpty()){
//                    providerId = providerInfo.getFirst().getId();
//                }
//            }
            var flowProperty = new FlowPropertyDao(db).getForName(exchange.get("unit_group")).getFirst();
            Long unitId = flowProperty.getReferenceUnit().id;
            Long propertyId = flowProperty.id;
            exchangeRequest.setFlowId(processRequestList.getFlowId());
            exchangeRequest.setFlowRefId(processRequestList.getFlowRefId());
            exchangeRequest.setUnitId(unitId);
            exchangeRequest.setPropertyId(propertyId);
            exchangeRequest.setAmount(amount);
            exchangeRequest.setDefaultProviderId(providerId);

            if("产品".equals(ioType)||"输出".equals(ioType)){
                exchangeRequest.setFlowId(processRequestList.getFlowId());
                exchangeRequest.setFlowRefId(processRequestList.getFlowRefId());
                exchangeRequest.setUnitId(unitId);
                exchangeRequest.setPropertyId(propertyId);
                exchangeRequest.setAmount(amount);
                exchangeRequest.setDefaultProviderId(providerId);
                outputIds.add(exchangeRequest);
            }

            if("输入".equals(ioType)){
                exchangeRequest.setFlowId(id);
                exchangeRequest.setFlowRefId(refId);
                exchangeRequest.setUnitId(unitId);
                exchangeRequest.setPropertyId(propertyId);
                exchangeRequest.setAmount(amount);
                exchangeRequest.setDefaultProviderId(providerId);
                inputIds.add(exchangeRequest);
            }
        }
        processRequestList.setInputIds(inputIds);
        processRequestList.setOutputIds(outputIds);


        return processRequestList;

    }

    /**
     * 使用雪花算法生成16为的id
     */
    public Long getSnowflakeId() {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();
        // 固定16位
        return id % 10000000000000000L;
    }


}
